import {Injectable} from '@angular/core';
import { TokenService } from '../token';

@Injectable()
export class UploadFileServer  {

  constructor(
    private _tokenService: TokenService,
  ) { };

  upload(url: string, files: File) {
    let token = this._tokenService.getToken().token;
    return new Promise((resolve, reject) => {
      let formData: any = new FormData();
      const xhr = new XMLHttpRequest();
      // formData.append('file', files);
      formData.append('image', files);
      xhr.onreadystatechange = function () {
        if (xhr.readyState === 4) {
          if (xhr.status === 200) {
            resolve(JSON.parse(xhr.response));
          } else {
            reject(xhr.response);
          }
        }
      };
      xhr.open('POST', url, true);
      xhr.setRequestHeader('Authorization', 'Bearer ' + token) ;
      xhr.send(formData);
    });
  }
  
  uploadImage(url: string, files: File , blob) {
    let token = this._tokenService.getToken().token;
    return new Promise((resolve, reject) => {
      let formData: any = new FormData();
      const xhr = new XMLHttpRequest();
      // formData.append('picture', files);
      formData.append('image', blob);
      // formData.append('image2', blob);
      // formData.append('blob', blob);
      xhr.onreadystatechange = function () {
        if (xhr.readyState === 4) {
          if (xhr.status === 200) {
            resolve(JSON.parse(xhr.response));
          } else {
            reject(xhr.response);
          }
        }
      };
      xhr.open('POST', url, true);
      xhr.setRequestHeader('Authorization', 'Bearer ' + token) ;
      xhr.send(formData);
    });
  }


}
